//
//  NewsHeadView.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/9/20.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import FSPagerView

@objc protocol NewsHeadViewDelegate {
    @objc optional func selectTitleImage(model:NewsPageModel) //选择图片标签
    @objc optional func changeHeadViewFrame() //改变头部视图坐标
}

class NewsHeadView: UIView {
    
    weak var newsDelegate : NewsHeadViewDelegate?
    
    fileprivate let cellId = "newsHeadCell"
    
    var dataArray = [NewsPageModel]()
    
    var imageUrl  = "" {
        didSet{
           getData()
        }
    }
    
    fileprivate lazy var pageView : FSPagerView = {
       
        let pagerView = FSPagerView()
        pagerView.delegate = self
        pagerView.dataSource = self
        pagerView.register(NewsHeadCell.self, forCellWithReuseIdentifier: cellId)
        pagerView.scrollDirection = .horizontal
        pagerView.itemSize = pagerView.frame.size
        pagerView.isInfinite = true //自动切换
        pagerView.automaticSlidingInterval = 5.0 //自动切换时间
        
        return pagerView
        
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(pageView)
        
        pageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
    }
    
    //MARK: 获取数据
    func getData() {
        
        if self.dataArray.count == 0 {
            //读取资讯缓存数据
            switch self.imageUrl {
            case url_informationNews://资讯新闻
                if NSKeyedUnarchiver.unarchiveObject(withFile: informationNewsTitle) != nil {
                    
                    self.dataArray = NSKeyedUnarchiver.unarchiveObject(withFile: informationNewsTitle) as! [NewsPageModel]
                    self.pageView.reloadData()
                }
            case url_financialNews://理财新闻
                if NSKeyedUnarchiver.unarchiveObject(withFile: financialNewsTitle) != nil {
                    
                    self.dataArray = NSKeyedUnarchiver.unarchiveObject(withFile: financialNewsTitle) as! [NewsPageModel]
                    self.pageView.reloadData()
                }
            case url_loanNews://贷款新闻
                if NSKeyedUnarchiver.unarchiveObject(withFile: loanNewsTitle) != nil {
                    
                    self.dataArray = NSKeyedUnarchiver.unarchiveObject(withFile: loanNewsTitle) as! [NewsPageModel]
                    self.pageView.reloadData()
                }
            default:
                break
            }
        }
        
        KMTool.requestGetData(URLString: imageUrl, parameters: nil, success: { (data) in
            
            
//            let elements = ["//ul[@class='list']/li/a","//ul[@class='list']/li/a/img","//ul[@class='list']/li/a/p"]
            let elements = ["//div[@id='lunbo']/div[@class='swiper-wrapper']/div[@class='swiper-slide swiper-slide-active']/a","//div[@id='lunbo']/div[@class='swiper-wrapper']/div[@class='swiper-slide swiper-slide-active']/a/img","//div[@id='lunbo']/div[@class='swiper-wrapper']/div[@class='swiper-slide swiper-slide-active']/a/p","//div[@id='lunbo']/div[@class='swiper-wrapper']/div[@class='swiper-slide swiper-slide-active']/a/p/span[@class='num']"]
            let attributes = ["href","src","text","text"]
            let keys = ["href","image","title","page"]
            let array = KMTool.htmlToModel(data: data, elements: elements, attributes: attributes, keys: keys)
            
            if array.count > 0 {
                self.dataArray.removeAll()
            }
            
            for item in array {
                let model = NewsPageModel.setModel(with: item)
                self.dataArray.append(model)
            }
            
            if self.dataArray.count > 0 {
                self.newsDelegate?.changeHeadViewFrame!()
                
                //缓存资讯内容
                switch self.imageUrl {
                case url_informationNews://资讯新闻
                NSKeyedArchiver.archiveRootObject(self.dataArray, toFile: informationNewsTitle)
                case url_financialNews://理财新闻
                NSKeyedArchiver.archiveRootObject(self.dataArray, toFile: financialNewsTitle)
                case url_loanNews://贷款新闻
                NSKeyedArchiver.archiveRootObject(self.dataArray, toFile: loanNewsTitle)
                default:
                    break
                }
            }
            
            
            
            self.pageView.reloadData()
        }) {
            
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension NewsHeadView : FSPagerViewDelegate,FSPagerViewDataSource {
    
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        
        return dataArray.count
    }
    
    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: cellId, at: index) as? NewsHeadCell
        cell?.model = dataArray[index]
//        cell?.pageLabel.text = "\(index+1)" + "/" + "\(self.dataArray.count)"
        return cell!
    }
    
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        pagerView.deselectItem(at: index, animated: true)
        
        self.newsDelegate?.selectTitleImage!(model: dataArray[index])

    }
    
    
}




